package com.mission.game.playgame;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.mission.game.R;
import com.mission.game.components.Statusable.Status;
import com.mission.game.utils.BarcodeTask;
import com.mission.game.utils.Task;

public class PlayBarcodeTask extends PlayAbstractTask {

	private TextView _barcodeResultView;
	private boolean _wasScanned = false;

	@Override
	protected int getContentView() {
		return R.layout.play_barcode_task;
	}

	@Override
	protected int getNameInput() {
		return R.id.play_barcode_name;
	}

	@Override
	protected int getDescriptionInput() {
		return R.id.play_barcode_description;
	}

	@Override
	protected void setSpecificFields() {
		_barcodeResultView = (TextView) findViewById(R.id.play_barcode_result);
		String userScan = ((BarcodeTask) _task).getUserScan();
		if (!userScan.isEmpty()) {
			_barcodeResultView.setText(userScan);
		}
	}

	public void onScanBarcodeClicked(View v) {
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent);
		if (scanResult != null) {
			if (_barcodeResultView == null) {
				_barcodeResultView = (TextView) findViewById(R.id.play_barcode_result);
			}
			// Put scan result into result EditText view
			_barcodeResultView.setText(scanResult.getContents());
			_wasScanned = true;
		}
		// else continue with any other code you need in the method
	}

	@Override
	public void onBackToMissionClicked(View v) {
		if (_barcodeResultView != null) {
			String result = _barcodeResultView.getText().toString();
			((BarcodeTask) _task).setUserScan(result);
			if (_wasScanned) {
				if (result.equals(((BarcodeTask) _task).getBarcodeContents())) {
					_task.setStatus(Status.COMPLETED);
				} else {
					_task.setStatus(Status.REJECTED);
				}
			}
		} else
			_task.setStatus(Task.Status.COMPLETED); // DEMO MODE! TODO: remove
													// for production
		getIntent().putExtra("task", _task);
		setResult(RESULT_OK, getIntent());
		finish();
	}
}
